package chu.dejian.ui.unused;

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;


import java.util.ArrayList;
import java.util.List;

import chu.dejian.adapter.AttentionAdapter;
import chu.dejian.adapter.AttentionMessageAdapter;

import com.sam.ble.unimplements.BLEBRHelper;
import com.sam.blemodule.R;
import chu.dejian.entity.ContactEntity;
import chu.dejian.entity.MeasureMessageEntity;
import chu.dejian.entity.ReceivedRequestEntity;
import chu.dejian.models.GetAttendeesResponse;
import chu.dejian.models.GetAttenderMessagesResponse;
import chu.dejian.models.GetReceivedAttenderRequestResponse;
import chu.dejian.models.PutAttendeesRequest;
import chu.dejian.models.PutAttenderRequestRequest;
import chu.dejian.models.PutAttenderRequestResponse;
import chu.dejian.restApi.RestClient;
import com.sam.ui.base.fragment.BaseFragment;
import com.sam.utils.display.DensityUtils;
import com.sam.utils.L;
import com.sam.utils.T;
import com.sam.widget.listview.deprecate_menu_list.SwipeMenu;
import com.sam.widget.listview.deprecate_menu_list.SwipeMenuCreator;
import com.sam.widget.listview.deprecate_menu_list.SwipeMenuItem;
import com.sam.widget.listview.deprecate_menu_list.SwipeMenuListView;

import chu.dejian.widget.AttentionLevelView;
import chu.dejian.widget.ViewPagerNavBar;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

public class AttentionOfMineFragment extends BaseFragment{
	private static AttentionOfMineFragment instance;
	private ViewPagerNavBar navBar;
	private ViewPager viewpager;
	private AttentionAdapter attendeeAdapter,attentionRequestAdapter;
	private AttentionMessageAdapter attentionMessageAdapter;
	private List<ContactEntity> attendeeList,attentionRequestList;
	private List<MeasureMessageEntity> measureMessageList;
	private static int newAttendeesCounts = 0,newMessageCounts = 0,newRequestCounts = 0;
	private AnsyncDataThread ansyncDataThread = new AnsyncDataThread();

	public synchronized static AttentionOfMineFragment getInstance(){
		if(instance == null){
			instance = new AttentionOfMineFragment();
		}
		return instance;
	}

	private static final int UPDATE_ATTENDEES_LIST = 0;
	private static final int UPDATE_ATTENTION_MESSAGE_LIST = 1;
	private static final int UPDATE_ATTENTION_REQUEST = 2;
	private Handler handler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what){
				case UPDATE_ATTENDEES_LIST:
					navBar.setTabTagText(0,(int)msg.obj+"");
					attendeeAdapter.notifyDataSetChanged();
					break;
				case UPDATE_ATTENTION_MESSAGE_LIST:
					navBar.setTabTagText(1,(int)msg.obj+"");
					attentionMessageAdapter.notifyDataSetChanged();
					break;
				case UPDATE_ATTENTION_REQUEST:
					navBar.setTabTagText(2,(int)msg.obj+"");
					attentionRequestAdapter.notifyDataSetChanged();
					break;
			}
			super.handleMessage(msg);
		}
	};
	private void sendMessage(int msgWhat,Object msgObj){
		Message msg = new Message();
		msg.what = msgWhat;
		msg.obj = msgObj;
		handler.sendMessage(msg);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fragment_attention_of_mine);
	}

	@Override
	public void findView() {
		navBar = (ViewPagerNavBar) findViewById(R.id.nav_bar);
		viewpager = (ViewPager) findViewById(R.id.view_pager);
	}

	@Override
	public void initView() {
		SwipeMenuListView attentionContactListView = new SwipeMenuListView(getActivity());
		View attentionMessagePage = View.inflate(getActivity(),R.layout.page_attention_message_list,null);
		ListView attentionMessageListView = (ListView) attentionMessagePage.findViewById(R.id.attention_list);
		EditText searchET = (EditText) attentionMessagePage.findViewById(R.id.search_et);
		searchET.addTextChangedListener(textWatcher);
		SwipeMenuListView attentionRequestListView = new SwipeMenuListView(getActivity());

		ViewPager.LayoutParams lp = new ViewPager.LayoutParams();
		lp.width = ViewPager.LayoutParams.MATCH_PARENT;
		lp.height = ViewPager.LayoutParams.MATCH_PARENT;

		attentionContactListView.setLayoutParams(lp);
		attentionRequestListView.setLayoutParams(lp);

		Drawable sepratorLineDrawable = new ColorDrawable(getResources().getColor(R.color.separator_line_bg));
		attentionContactListView.setDivider(sepratorLineDrawable);
		attentionRequestListView.setDivider(sepratorLineDrawable);
		attentionContactListView.setDividerHeight(1);
		attentionRequestListView.setDividerHeight(1);

		attentionContactListView.setMenuCreator(contactMenuCreator);
		attentionContactListView.setOnMenuItemClickListener(contactsMenuClickListener);
//		attentionContactListView.setOnItemClickListener(onItemClickListener);
//		attentionContactListView.setOnSwipeListener(onSwipeListener);

		attentionRequestListView.setMenuCreator(requestMenuCreator);
		attentionRequestListView.setOnMenuItemClickListener(requestMenuClickListener);
//		attentionRequestListView.setOnItemClickListener(onItemClickListener);
//		attentionRequestListView.setOnSwipeListener(onSwipeListener);

		attendeeList = new ArrayList<>();
		measureMessageList = new ArrayList<>();
		attentionRequestList = new ArrayList<>();

		attendeeAdapter = new AttentionAdapter(getActivity(),R.layout.row_attention_vertical,attendeeList,false);
		attentionMessageAdapter = new AttentionMessageAdapter(getActivity(),measureMessageList);
		attentionRequestAdapter = new AttentionAdapter(getActivity(),R.layout.row_attention_vertical,attentionRequestList,false);

		attentionContactListView.setAdapter(attendeeAdapter);
		attentionMessageListView.setAdapter(attentionMessageAdapter);
		attentionRequestListView.setAdapter(attentionRequestAdapter);

		List<View> pages = new ArrayList<View>();
		pages.add(attentionContactListView);
		pages.add(attentionMessagePage);
		pages.add(attentionRequestListView);

		navBar.setPages(viewpager,pages);
		navBar.setCurrentTab(1);
		navBar.setOnPageChangeCallback(new ViewPagerNavBar.OnPageChangeCallback(){
			@Override
			public void onPageChanged(final int position) {
				handler.postDelayed(new Runnable() {
					@Override
					public void run() {
						navBar.hideTabTag(position);
					}
				},3000);
			}
		});
	}

	@Override
	public void onResume() {
		super.onResume();
		newAttendeesCounts = newMessageCounts = newRequestCounts = 0;
		ansyncDataThread.stop();
		ansyncDataThread.start();
		navBar.resetCursorLine();
	}

	private boolean isAnsyncAttendees = false;
	private void asyncAttendees(int startPage){
		if(isAnsyncAttendees) return;
		isAnsyncAttendees = true;
		RestClient.getAuthedClient().getApiService().getAttendees(startPage,new Callback<GetAttendeesResponse>() {
			@Override
			public void success(GetAttendeesResponse getAttendeesResponse, Response response) {
				if(response.getStatus() == 401) {
					BLEBRHelper.getInstance().sendReloginBR(getActivity());
					T.showShort(getActivity(),R.string.nauthorized_and_relogin);
					return;
				}
				L.d("《获取当前用户或提供者关注的用户列表-getAttendees》\n请求成功： \n\t返回数据：" + getAttendeesResponse.toString());
				final List<GetAttendeesResponse.ResultsEntity> attendees = getAttendeesResponse.getResults();
				if(attendees == null || attendees.size() == 0) return;
				for(GetAttendeesResponse.ResultsEntity attendee : attendees){
					ContactEntity contactEntity = new ContactEntity(attendee.getAtid(),attendee.getAttendee_name(),attendee.getAttendee(),attendee.getAttendee_level());
					if(!attendeeList.contains(contactEntity)){
						attendeeList.add(contactEntity);
						newAttendeesCounts++;
					}
				}
				isAnsyncAttendees = false;
				if(getAttendeesResponse.getNext() != null && !getAttendeesResponse.getNext().equals("null")){
					int nextPage = Integer.parseInt(Uri.parse(getAttendeesResponse.getNext()).getQueryParameter("page"));
					asyncAttendees(nextPage);
				} else {
					if(newAttendeesCounts > 0) sendMessage(UPDATE_ATTENDEES_LIST,newAttendeesCounts);
					else navBar.hideTabTag(0);
				}
			}

			@Override
			public void failure(RetrofitError retrofitError) {
				L.d("《获取当前用户或提供者关注的用户列表-getAttendees》\n请求失败： \n\t错误信息：" + retrofitError.toString());
			}
		});
	}

	private boolean isAnsyncMessage = false;
	private void asyncMessage(int startPage){
		if(isAnsyncMessage) return;
		isAnsyncMessage = true;
		RestClient.getAuthedClient().getApiService().getAttenderMessage(startPage,1, new Callback<GetAttenderMessagesResponse>() {
			@Override
			public void success(GetAttenderMessagesResponse getAttenderMessagesResponse, Response response) {
				if(response.getStatus() == 401) {
					BLEBRHelper.getInstance().sendReloginBR(getActivity());
					T.showShort(getActivity(),R.string.nauthorized_and_relogin);
					return;
				}
				L.d("《获取关注消息-getAttenderMessage》\n请求成功： \n\t返回数据：" + getAttenderMessagesResponse.toString());
				final List<GetAttenderMessagesResponse.ResultsEntity> messages = getAttenderMessagesResponse.getResults();
				if (messages == null || messages.size() == 0) return;
				for (GetAttenderMessagesResponse.ResultsEntity message : messages) {
					MeasureMessageEntity measureMessage = message.toMeasureMessageEntity();
					if(!measureMessageList.contains(measureMessage)){
						measureMessageList.add(measureMessage);
						newMessageCounts++;
					}
				}
				isAnsyncMessage = false;
				if(getAttenderMessagesResponse.getNext() != null && !getAttenderMessagesResponse.getNext().equals("null")){
					int nextPage = Integer.parseInt(Uri.parse(getAttenderMessagesResponse.getNext()).getQueryParameter("page"));
					asyncAttendees(nextPage);
				} else {
					if(newMessageCounts > 0) sendMessage(UPDATE_ATTENTION_MESSAGE_LIST,newMessageCounts);
					else navBar.hideTabTag(1);
				}
			}

			@Override
			public void failure(RetrofitError retrofitError) {
				L.d("《获取关注消息-getAttenderMessage》\n请求失败： \n\t错误信息：" + retrofitError.toString());
			}
		});
	}

	private boolean isAnsyncRequest = false;
	private void asyncRequest(int startPage){
		if(isAnsyncRequest) return;
		isAnsyncRequest = true;
		RestClient.getAuthedClient().getApiService().getReceivedAttenderRequest(startPage,new Callback<GetReceivedAttenderRequestResponse>() {
			@Override
			public void success(GetReceivedAttenderRequestResponse getReceivedAttenderRequestResponse, Response response) {
				if(response.getStatus() == 401) {
					BLEBRHelper.getInstance().sendReloginBR(getActivity());
					T.showShort(getActivity(),R.string.nauthorized_and_relogin);
					return;
				}
				L.d("《获取收到的关注请求-getReceivedAttenderRequest》\n请求成功： \n\t返回数据：" + getReceivedAttenderRequestResponse.toString());
				final List<GetReceivedAttenderRequestResponse.ResultsEntity> resultEntities = getReceivedAttenderRequestResponse.getResults();
				if (resultEntities == null || resultEntities.size() == 0) return;
				for (GetReceivedAttenderRequestResponse.ResultsEntity resultsEntity : resultEntities) {
					ContactEntity contactEntity = new ContactEntity(resultsEntity.getAr_id(), resultsEntity.getAttendee_name(), resultsEntity.getAttendee(), resultsEntity.getAttendee_level());
					if(resultsEntity.getStatus() == ReceivedRequestEntity.STATUS_PENDING && !attentionRequestList.contains(contactEntity)){
						attentionRequestList.add(contactEntity);
						newRequestCounts++;
					}
				}
				isAnsyncRequest = false;
				if(getReceivedAttenderRequestResponse.getNext() != null && !getReceivedAttenderRequestResponse.getNext().equals("null")){
					int nextPage = Integer.parseInt(Uri.parse(getReceivedAttenderRequestResponse.getNext()).getQueryParameter("page"));
					asyncRequest(nextPage);
				} else {
					if(newRequestCounts > 0) sendMessage(UPDATE_ATTENTION_REQUEST,newRequestCounts);
					else navBar.hideTabTag(2);
				}
			}

			@Override
			public void failure(RetrofitError retrofitError) {
				L.d("《获取收到的关注请求-getReceivedAttenderRequest》\n请求失败： \n\t错误信息：" + retrofitError.toString());
				T.showLong(getActivity(), R.string.get_data_from_webserver_failed);
			}
		});
	}

	private TextWatcher textWatcher = new TextWatcher() {
		@Override
		public void beforeTextChanged(CharSequence s, int start, int count, int after) {
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
			attentionMessageAdapter.getFilter().filter(s);
		}

		@Override
		public void afterTextChanged(Editable s) {

		}
	};

	private SwipeMenuListView.OnMenuItemClickListener contactsMenuClickListener = new SwipeMenuListView.OnMenuItemClickListener() {
		@Override
		public boolean onMenuItemClick(final int position, SwipeMenu menu, int index) {
			switch (index) {
				case 0: //取消关注
					final int p = attendeeList.size()  - 1 - position; // 倒序显示
					final int attendId = attendeeList.get(p).id;
					final int level = AttentionLevelView.ATTENTION_LEVEL.NOTIFY_NOTHING.ordinal();
					RestClient.getAuthedClient().getApiService().putAttendees(attendId, new PutAttendeesRequest(level), new Callback() {
						@Override
						public void success(Object o, Response response) {
							if(response.getStatus() == 401) {
								BLEBRHelper.getInstance().sendReloginBR(getActivity());
								T.showShort(getActivity(),R.string.nauthorized_and_relogin);
								return;
							}
							L.d("《修改关注-putAttendees》", "请求成功： \n\t返回数据：" + o.toString());
							if(response.getStatus() == 200) {
								attendeeList.remove(p);
								attendeeAdapter.notifyDataSetChanged();
							} else T.showLong(getActivity(), R.string.cancel_attention_failed);
						}

						@Override
						public void failure(RetrofitError retrofitError) {
							L.d("《修改关注-putAttendees》", "请求失败： \n\t错误信息：" + retrofitError.toString());
							T.showLong(getActivity(), R.string.cancel_attention_failed);
						}
					});
					break;
			}
			return false;
		}
	};
	private SwipeMenuListView.OnMenuItemClickListener requestMenuClickListener = new SwipeMenuListView.OnMenuItemClickListener() {
		@Override
		public boolean onMenuItemClick(final int position, SwipeMenu menu, int index) {
			final int p = attentionRequestList.size()  - 1 - position; // 倒序显示
			final int attentionId = attentionRequestList.get(p).id;
			switch (index) {
				case 0: //接受
					int level = attentionRequestList.get(p).attentionLevel.ordinal();
					PutAttenderRequestRequest putAttenderRequestRequest = new PutAttenderRequestRequest(PutAttenderRequestRequest.ACTION_ID_ACCEPT,level);
					RestClient.getAuthedClient().getApiService().putAttenderRequest(attentionId, putAttenderRequestRequest, new Callback<PutAttenderRequestResponse>() {
						@Override
						public void success(PutAttenderRequestResponse putAttenderRequestResponse, Response response) {
							if(response.getStatus() == 401) {
								BLEBRHelper.getInstance().sendReloginBR(getActivity());
								T.showShort(getActivity(),R.string.nauthorized_and_relogin);
								return;
							}
							String requestStr = putAttenderRequestResponse == null ? "null" : putAttenderRequestResponse.toString();
							L.d("《对关注请求执行操作-putAttenderRequest》", "请求成功： \n\t返回数据：" + requestStr );
							if(response.getStatus() == 200){
								attentionRequestList.remove(p);
								attentionRequestAdapter.notifyDataSetChanged();
							} else T.showShort(getActivity(), R.string.process_failed);
						}

						@Override
						public void failure(RetrofitError retrofitError) {
							L.d("《对关注请求执行操作-putAttenderRequest》", "请求失败： \n\t错误信息：" + retrofitError.toString());
							T.showShort(getActivity(), R.string.process_failed);
						}
					});
					break;
				case 1: //拒绝
					putAttenderRequestRequest = new PutAttenderRequestRequest(PutAttenderRequestRequest.ACTION_ID_REFUSE,0);
					RestClient.getAuthedClient().getApiService().putAttenderRequest(attentionId, putAttenderRequestRequest, new Callback<PutAttenderRequestResponse>() {
						@Override
						public void success(PutAttenderRequestResponse putAttenderRequestResponse, Response response) {
							if(response.getStatus() == 401) {
								BLEBRHelper.getInstance().sendReloginBR(getActivity());
								T.showShort(getActivity(),R.string.nauthorized_and_relogin);
								return;
							}
							String requestStr = putAttenderRequestResponse == null ? "null" : putAttenderRequestResponse.toString();
							L.d("《对关注请求执行操作-putAttenderRequest》", "请求成功： \n\t返回数据：" + requestStr);
							if(response.getStatus() == 200){
								attentionRequestList.remove(p);
								attentionRequestAdapter.notifyDataSetChanged();
							} else T.showShort(getActivity(), R.string.process_failed);

						}

						@Override
						public void failure(RetrofitError retrofitError) {
							L.d("《对关注请求执行操作-putAttenderRequest》", "请求失败： \n\t错误信息：" + retrofitError.toString());
							T.showShort(getActivity(), R.string.process_failed);
						}
					});
					break;
			}
			return false;
		}
	};

	private AdapterView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			T.showShort(getActivity(),position + " 项被点击");
		}
	};

	SwipeMenuCreator contactMenuCreator = new SwipeMenuCreator() {

		@Override
		public void create(SwipeMenu menu) {
			SwipeMenuItem inattentionBtn = new SwipeMenuItem(getActivity());
			Drawable inattentionBg = new ColorDrawable(getResources().getColor(R.color.orange_menu_bg_color));
			inattentionBtn.setBackground(inattentionBg);
			inattentionBtn.setWidth(DensityUtils.dp2px(getActivity(), 80));
			inattentionBtn.setTitle(R.string.inattention);
			inattentionBtn.setTitleSize(16);
			inattentionBtn.setTitleColor(Color.WHITE);
			menu.addMenuItem(inattentionBtn);
		}
	};
	SwipeMenuCreator requestMenuCreator = new SwipeMenuCreator() {

		@Override
		public void create(SwipeMenu menu) {
			SwipeMenuItem acceptBtn = new SwipeMenuItem(getActivity());
			Drawable acceptBg = new ColorDrawable(getResources().getColor(R.color.blue_menu_bg_color));
			acceptBtn.setBackground(acceptBg);
			acceptBtn.setWidth(DensityUtils.dp2px(getActivity(), 60));
			acceptBtn.setTitle(R.string.accept);
			acceptBtn.setTitleSize(16);
			acceptBtn.setTitleColor(Color.WHITE);
			menu.addMenuItem(acceptBtn);

			SwipeMenuItem refuseBtn = new SwipeMenuItem(getActivity());
			Drawable refuseBg = new ColorDrawable(getResources().getColor(R.color.orange_menu_bg_color));
			refuseBtn.setBackground(refuseBg);
			refuseBtn.setWidth(DensityUtils.dp2px(getActivity(), 60));
			refuseBtn.setTitle(R.string.refuse);
			refuseBtn.setTitleSize(16);
			refuseBtn.setTitleColor(Color.WHITE);
			menu.addMenuItem(refuseBtn);
		}
	};

	private SwipeMenuListView.OnSwipeListener onSwipeListener = new SwipeMenuListView.OnSwipeListener() {

		@Override
		public void onSwipeStart(int position) {
			// swipe start
		}

		@Override
		public void onSwipeEnd(int position) {
			// swipe end
		}
	};

	class AnsyncDataThread implements Runnable {
		public boolean running = false;
		private Thread thread = null;

		public void run() {
			asyncAttendees(1);
			asyncMessage(1);
			asyncRequest(1);
		}

		public void start() {
			this.thread = new Thread(this);
			this.running = true;
			this.thread.start();
		}

		public void stop() {
			this.running = false;
			this.thread = null;
		}
	}
}
